package sdk.chat.core.dao;

import android.database.Cursor;
import android.database.sqlite.SQLiteStatement;

import org.greenrobot.greendao.AbstractDao;
import org.greenrobot.greendao.Property;
import org.greenrobot.greendao.database.Database;
import org.greenrobot.greendao.database.DatabaseStatement;
import org.greenrobot.greendao.internal.DaoConfig;
import org.greenrobot.greendao.internal.SqlUtils;
import org.greenrobot.greendao.query.Query;
import org.greenrobot.greendao.query.QueryBuilder;

import java.util.ArrayList;
import java.util.List;

// THIS CODE IS GENERATED BY greenDAO, DO NOT EDIT.
/**
 * DAO for table "ThreadXX".
 */
public class ThreadDao extends AbstractDao<ThreadX, Long> {

    public static final String TABLENAME = "ThreadX";

    /**
     * Properties of entity ThreadX.<br/>
     * Can be used for QueryBuilder and for referencing column names.
     */
    public static class Properties {
        public final static Property Id = new Property(0, Long.class, "id", true, "_id");
        public final static Property EntityID = new Property(1, String.class, "entityID", false, "ENTITY_ID");
        public final static Property CreationDate = new Property(2, java.util.Date.class, "creationDate", false, "CREATION_DATE");
        public final static Property Type = new Property(3, Integer.class, "type", false, "TYPE");
        public final static Property CreatorId = new Property(4, Long.class, "creatorId", false, "CREATOR_ID");
        public final static Property LoadMessagesFrom = new Property(5, java.util.Date.class, "loadMessagesFrom", false, "LOAD_MESSAGES_FROM");
        public final static Property Deleted = new Property(6, Boolean.class, "deleted", false, "DELETED");
        public final static Property Draft = new Property(7, String.class, "draft", false, "DRAFT");
        public final static Property CanDeleteMessagesFrom = new Property(8, java.util.Date.class, "canDeleteMessagesFrom", false, "CAN_DELETE_MESSAGES_FROM");
        public final static Property LastMessageId = new Property(9, Long.class, "lastMessageId", false, "LAST_MESSAGE_ID");
        public final static Property LastMessageDate = new Property(10, java.util.Date.class, "lastMessageDate", false, "LAST_MESSAGE_DATE");
    }

    private DaoSession daoSession;

    private Query<ThreadX> user_ThreadXsQuery;

    public ThreadDao(DaoConfig config) {
        super(config);
    }

    public ThreadDao(DaoConfig config, DaoSession daoSession) {
        super(config, daoSession);
        this.daoSession = daoSession;
    }

    /** Creates the underlying database table. */
    public static void createTable(Database db, boolean ifNotExists) {
        String constraint = ifNotExists? "IF NOT EXISTS ": "";
        db.execSQL("CREATE TABLE " + constraint + "\"ThreadX\" (" + //
                "\"_id\" INTEGER PRIMARY KEY ," + // 0: id
                "\"ENTITY_ID\" TEXT," + // 1: entityID
                "\"CREATION_DATE\" INTEGER," + // 2: creationDate
                "\"TYPE\" INTEGER," + // 3: type
                "\"CREATOR_ID\" INTEGER," + // 4: creatorId
                "\"LOAD_MESSAGES_FROM\" INTEGER," + // 5: loadMessagesFrom
                "\"DELETED\" INTEGER," + // 6: deleted
                "\"DRAFT\" TEXT," + // 7: draft
                "\"CAN_DELETE_MESSAGES_FROM\" INTEGER," + // 8: canDeleteMessagesFrom
                "\"LAST_MESSAGE_ID\" INTEGER," + // 9: lastMessageId
                "\"LAST_MESSAGE_DATE\" INTEGER);"); // 10: lastMessageDate
        // Add Indexes
        db.execSQL("CREATE UNIQUE INDEX " + constraint + "IDX_ThreadX_ENTITY_ID ON \"ThreadX\"" +
                " (\"ENTITY_ID\" ASC);");
        db.execSQL("CREATE INDEX " + constraint + "IDX_ThreadX_TYPE ON \"ThreadX\"" +
                " (\"TYPE\" ASC);");
        db.execSQL("CREATE INDEX " + constraint + "IDX_ThreadX_DELETED ON \"ThreadX\"" +
                " (\"DELETED\" ASC);");
    }

    /** Drops the underlying database table. */
    public static void dropTable(Database db, boolean ifExists) {
        String sql = "DROP TABLE " + (ifExists ? "IF EXISTS " : "") + "\"ThreadX\"";
        db.execSQL(sql);
    }

    @Override
    protected final void bindValues(DatabaseStatement stmt, ThreadX entity) {
        stmt.clearBindings();

        Long id = entity.getId();
        if (id != null) {
            stmt.bindLong(1, id);
        }

        String entityID = entity.getEntityID();
        if (entityID != null) {
            stmt.bindString(2, entityID);
        }

        java.util.Date creationDate = entity.getCreationDate();
        if (creationDate != null) {
            stmt.bindLong(3, creationDate.getTime());
        }

        Integer type = entity.getType();
        if (type != null) {
            stmt.bindLong(4, type);
        }

        Long creatorId = entity.getCreatorId();
        if (creatorId != null) {
            stmt.bindLong(5, creatorId);
        }

        java.util.Date loadMessagesFrom = entity.getLoadMessagesFrom();
        if (loadMessagesFrom != null) {
            stmt.bindLong(6, loadMessagesFrom.getTime());
        }

        Boolean deleted = entity.getDeleted();
        if (deleted != null) {
            stmt.bindLong(7, deleted ? 1L: 0L);
        }

        String draft = entity.getDraft();
        if (draft != null) {
            stmt.bindString(8, draft);
        }

        java.util.Date canDeleteMessagesFrom = entity.getCanDeleteMessagesFrom();
        if (canDeleteMessagesFrom != null) {
            stmt.bindLong(9, canDeleteMessagesFrom.getTime());
        }

        Long lastMessageId = entity.getLastMessageId();
        if (lastMessageId != null) {
            stmt.bindLong(10, lastMessageId);
        }

        java.util.Date lastMessageDate = entity.getLastMessageDate();
        if (lastMessageDate != null) {
            stmt.bindLong(11, lastMessageDate.getTime());
        }
    }

    @Override
    protected final void bindValues(SQLiteStatement stmt, ThreadX entity) {
        stmt.clearBindings();

        Long id = entity.getId();
        if (id != null) {
            stmt.bindLong(1, id);
        }

        String entityID = entity.getEntityID();
        if (entityID != null) {
            stmt.bindString(2, entityID);
        }

        java.util.Date creationDate = entity.getCreationDate();
        if (creationDate != null) {
            stmt.bindLong(3, creationDate.getTime());
        }

        Integer type = entity.getType();
        if (type != null) {
            stmt.bindLong(4, type);
        }

        Long creatorId = entity.getCreatorId();
        if (creatorId != null) {
            stmt.bindLong(5, creatorId);
        }

        java.util.Date loadMessagesFrom = entity.getLoadMessagesFrom();
        if (loadMessagesFrom != null) {
            stmt.bindLong(6, loadMessagesFrom.getTime());
        }

        Boolean deleted = entity.getDeleted();
        if (deleted != null) {
            stmt.bindLong(7, deleted ? 1L: 0L);
        }

        String draft = entity.getDraft();
        if (draft != null) {
            stmt.bindString(8, draft);
        }

        java.util.Date canDeleteMessagesFrom = entity.getCanDeleteMessagesFrom();
        if (canDeleteMessagesFrom != null) {
            stmt.bindLong(9, canDeleteMessagesFrom.getTime());
        }

        Long lastMessageId = entity.getLastMessageId();
        if (lastMessageId != null) {
            stmt.bindLong(10, lastMessageId);
        }

        java.util.Date lastMessageDate = entity.getLastMessageDate();
        if (lastMessageDate != null) {
            stmt.bindLong(11, lastMessageDate.getTime());
        }
    }

    @Override
    protected final void attachEntity(ThreadX entity) {
        super.attachEntity(entity);
        entity.__setDaoSession(daoSession);
    }

    @Override
    public Long readKey(Cursor cursor, int offset) {
        return cursor.isNull(offset + 0) ? null : cursor.getLong(offset + 0);
    }

    @Override
    public ThreadX readEntity(Cursor cursor, int offset) {
        ThreadX entity = new ThreadX( //
                cursor.isNull(offset + 0) ? null : cursor.getLong(offset + 0), // id
                cursor.isNull(offset + 1) ? null : cursor.getString(offset + 1), // entityID
                cursor.isNull(offset + 2) ? null : new java.util.Date(cursor.getLong(offset + 2)), // creationDate
                cursor.isNull(offset + 3) ? null : cursor.getInt(offset + 3), // type
                cursor.isNull(offset + 4) ? null : cursor.getLong(offset + 4), // creatorId
                cursor.isNull(offset + 5) ? null : new java.util.Date(cursor.getLong(offset + 5)), // loadMessagesFrom
                cursor.isNull(offset + 6) ? null : cursor.getShort(offset + 6) != 0, // deleted
                cursor.isNull(offset + 7) ? null : cursor.getString(offset + 7), // draft
                cursor.isNull(offset + 8) ? null : new java.util.Date(cursor.getLong(offset + 8)), // canDeleteMessagesFrom
                cursor.isNull(offset + 9) ? null : cursor.getLong(offset + 9), // lastMessageId
                cursor.isNull(offset + 10) ? null : new java.util.Date(cursor.getLong(offset + 10)) // lastMessageDate
        );
        return entity;
    }

    @Override
    public void readEntity(Cursor cursor, ThreadX entity, int offset) {
        entity.setId(cursor.isNull(offset + 0) ? null : cursor.getLong(offset + 0));
        entity.setEntityID(cursor.isNull(offset + 1) ? null : cursor.getString(offset + 1));
        entity.setCreationDate(cursor.isNull(offset + 2) ? null : new java.util.Date(cursor.getLong(offset + 2)));
        entity.setType(cursor.isNull(offset + 3) ? null : cursor.getInt(offset + 3));
        entity.setCreatorId(cursor.isNull(offset + 4) ? null : cursor.getLong(offset + 4));
        entity.setLoadMessagesFrom(cursor.isNull(offset + 5) ? null : new java.util.Date(cursor.getLong(offset + 5)));
        entity.setDeleted(cursor.isNull(offset + 6) ? null : cursor.getShort(offset + 6) != 0);
        entity.setDraft(cursor.isNull(offset + 7) ? null : cursor.getString(offset + 7));
        entity.setCanDeleteMessagesFrom(cursor.isNull(offset + 8) ? null : new java.util.Date(cursor.getLong(offset + 8)));
        entity.setLastMessageId(cursor.isNull(offset + 9) ? null : cursor.getLong(offset + 9));
        entity.setLastMessageDate(cursor.isNull(offset + 10) ? null : new java.util.Date(cursor.getLong(offset + 10)));
    }

    @Override
    protected final Long updateKeyAfterInsert(ThreadX entity, long rowId) {
        entity.setId(rowId);
        return rowId;
    }

    @Override
    public Long getKey(ThreadX entity) {
        if(entity != null) {
            return entity.getId();
        } else {
            return null;
        }
    }

    @Override
    public boolean hasKey(ThreadX entity) {
        return entity.getId() != null;
    }

    @Override
    protected final boolean isEntityUpdateable() {
        return true;
    }

    /** Internal query to resolve the "ThreadXs" to-many relationship of User. */
    public List<ThreadX> _queryUser_ThreadXs(Long userId) {
        synchronized (this) {
            if (user_ThreadXsQuery == null) {
                QueryBuilder<ThreadX> queryBuilder = queryBuilder();
                queryBuilder.join(UserThreadLink.class, UserThreadLinkDao.Properties.ThreadId)
                        .where(UserThreadLinkDao.Properties.UserId.eq(userId));
                user_ThreadXsQuery = queryBuilder.build();
            }
        }
        Query<ThreadX> query = user_ThreadXsQuery.forCurrentThread();
        query.setParameter(0, userId);
        return query.list();
    }

    private String selectDeep;

    protected String getSelectDeep() {
        if (selectDeep == null) {
            StringBuilder builder = new StringBuilder("SELECT ");
            SqlUtils.appendColumns(builder, "T", getAllColumns());
            builder.append(',');
            SqlUtils.appendColumns(builder, "T0", daoSession.getMessageDao().getAllColumns());
            builder.append(',');
            SqlUtils.appendColumns(builder, "T1", daoSession.getUserDao().getAllColumns());
            builder.append(" FROM ThreadX T");
            builder.append(" LEFT JOIN MESSAGE T0 ON T.\"LAST_MESSAGE_ID\"=T0.\"_id\"");
            builder.append(" LEFT JOIN USER T1 ON T.\"CREATOR_ID\"=T1.\"_id\"");
            builder.append(' ');
            selectDeep = builder.toString();
        }
        return selectDeep;
    }

    protected ThreadX loadCurrentDeep(Cursor cursor, boolean lock) {
        ThreadX entity = loadCurrent(cursor, 0, lock);
        int offset = getAllColumns().length;

        Message lastMessage = loadCurrentOther(daoSession.getMessageDao(), cursor, offset);
        entity.setLastMessage(lastMessage);
        offset += daoSession.getMessageDao().getAllColumns().length;

        User creator = loadCurrentOther(daoSession.getUserDao(), cursor, offset);
        entity.setCreator(creator);

        return entity;
    }

    public ThreadX loadDeep(Long key) {
        assertSinglePk();
        if (key == null) {
            return null;
        }

        StringBuilder builder = new StringBuilder(getSelectDeep());
        builder.append("WHERE ");
        SqlUtils.appendColumnsEqValue(builder, "T", getPkColumns());
        String sql = builder.toString();

        String[] keyArray = new String[] { key.toString() };
        Cursor cursor = db.rawQuery(sql, keyArray);

        try {
            boolean available = cursor.moveToFirst();
            if (!available) {
                return null;
            } else if (!cursor.isLast()) {
                throw new IllegalStateException("Expected unique result, but count was " + cursor.getCount());
            }
            return loadCurrentDeep(cursor, true);
        } finally {
            cursor.close();
        }
    }

    /** Reads all available rows from the given cursor and returns a list of new ImageTO objects. */
    public List<ThreadX> loadAllDeepFromCursor(Cursor cursor) {
        int count = cursor.getCount();
        List<ThreadX> list = new ArrayList<ThreadX>(count);

        if (cursor.moveToFirst()) {
            if (identityScope != null) {
                identityScope.lock();
                identityScope.reserveRoom(count);
            }
            try {
                do {
                    list.add(loadCurrentDeep(cursor, false));
                } while (cursor.moveToNext());
            } finally {
                if (identityScope != null) {
                    identityScope.unlock();
                }
            }
        }
        return list;
    }

    protected List<ThreadX> loadDeepAllAndCloseCursor(Cursor cursor) {
        try {
            return loadAllDeepFromCursor(cursor);
        } finally {
            cursor.close();
        }
    }


    /** A raw-style query where you can pass any WHERE clause and arguments. */
    public List<ThreadX> queryDeep(String where, String... selectionArg) {
        Cursor cursor = db.rawQuery(getSelectDeep() + where, selectionArg);
        return loadDeepAllAndCloseCursor(cursor);
    }

}